package com.edu.app.shiro;

import com.edu.app.constant.ErrorConstant;
import com.edu.app.exception.UnauthorizedException;
import com.edu.app.util.ErrorUtil;

import org.apache.shiro.ShiroException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionController {

    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public ModelMap handle401(ShiroException e) {
        return ErrorUtil.retErrMsg(e);
    }

    // 捕捉UnauthorizedException
    @ExceptionHandler(UnauthorizedException.class)
    public ModelMap handle401() {
        return ErrorUtil.retErrMsg(ErrorConstant.ACCESS_DENIED);
    }

    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public ModelMap globalException(Exception e) {
        return ErrorUtil.retErrMsg(e);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ModelMap globalException(DuplicateKeyException e) {
        return ErrorUtil.retErrMsg(e);
    }

    /*
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }*/
}
